<template>
  <div id="baiduSearchG" class="move-search" ref="MoveSearchApp" :style="modalPosition" v-if="show && results && results.length">
    <div class="move-search-content">
      <ul class="move-search-ul" v-for="data in results" :key="data.id">
        <li class="move-search-li">
          <a :href="data.url" target="_blank">
            {{data.title}}
          </a>
          <span>{{data.summary}}</span>
        </li>
      </ul>
    </div>
    <div class="move-search-bottom-fade"></div>
    <footer class="move-search-footer">
      <a :href="`https://kaifa.baidu.com/searchPage?wd=${selectedText}`" target="_blank">
        Read More
      </a>
    </footer>
  </div>
</template>
<script>
import './app.less'
import axios from 'axios'

const MODAL_WIDTH = 350

export default {
  data: function() {
    return {
      results: '',
      show: false,
      selectedText: '',
      modalPosition: {
        left: 0,
        top: 0,
      },
    }
  },
  mounted() {
    document.addEventListener('mouseup', (e) => {
      let selectionObj = window.getSelection()
      let selectedText = selectionObj.toString()
      if (selectedText.length === 0) {
        if (this.show) {
          // 重新计算是否关闭弹窗
          // 检测鼠标位置是否在弹窗内，不是则关闭弹窗
          var inModal = this.boundaryDetection(
            e.clientX,
            e.clientY,
            this.modalPosition
          )
          if (!inModal) {
            this.show = false
            this.results = []
          }
        }
      } else {
        let selectionObjRect = selectionObj.getRangeAt(0).getBoundingClientRect()
        let { x, y, height, width } = selectionObjRect // 获取选中文字的位置，x y是横纵坐标，height width是选中文字的高度和宽度
        // 计算弹窗位置，算出left和top
        let left = x - MODAL_WIDTH / 2 + width / 2
        left = left > 10 ? left : 10
        let top = y + height
        let scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft
        let scrollTop = document.documentElement.scrollTop || document.body.scrollTop
        axios
          .get(
            `https://movesearch.vercel.app/api/baidu?query=${selectedText}&pageNum=1&pageSize=10`
          )
          .then((res) => {
            let { data } = res.data.data.documents
            if (data.length) {
              this.show = true
              this.results = data
              this.selectedText = selectedText
              this.modalPosition = {
                left: left + scrollLeft + 'px',
                top: top + scrollTop + 'px',
              }
            }
          })
      }
    })
  },
  methods: {
    handleClose() {
      this.show = !this.show
    },
    boundaryDetection(x, y, modalPosition = { left: 0, top: 0 }) {
      let { left, top } = modalPosition
      if (
        x > left &&
        x < left + MODAL_WIDTH &&
        y > top &&
        y < top + this.refs['MoveSearchApp'].offsetHeight
      ) {
        return true
      }
      return false
    }
  }
}
</script>
<style scoped>
</style>
